-module(parallel_alg).
-export([parallel_cliques/3]).


%%%
parallel_cliques(Graph, SlavePID, MasterPID)->
    send_task(graph:v(Graph),
	      [],
	      [],
	      Graph,
	      MasterPID),
    finish(SlavePID, MasterPID).
    

parrallel_cliques(N,D,S,G, SlavePID, MasterPID)->
    case set:empty(set:join(N,D)) of
	true ->
	    MasterPID!{result_process, S},
	    finish(SlavePID, MasterPID);
	false -> case set:empty(N) of
		    false ->
			F = set:get_el(N),
			NewN = set:diff(N, [F]),
			send_task( set:cross(NewN, graph:adj(F, G)),
				   set:cross(D,
					     graph:adj(F, G)),
				   set:add(F,S),
				   G,
				   MasterPID),
			loop(NewN,
			     set:add(F,D),
			     S,
			     set:cross(NewN,
				       set:diff(graph:v(G),graph:adj(F,G))),
			     G,
			     MasterPID),
			 finish(SlavePID, MasterPID);
		    true -> finish(SlavePID, MasterPID)
		end
    end.

loop(_,_,_,[],_,_)->
    ok;
loop(N, D, S, [F | Tail], G, MasterPID)->
    NewN = set:diff(N, [F]),
    send_task( set:cross(NewN, graph:adj(F,G)),
	       set:cross(D, graph:adj(F,G)),
	       set:add(F,S),
	       G,
	       MasterPID),
    loop(NewN,
	 set:add(F,D),
	 S,
	 Tail,
	 G,
	 MasterPID).

%%% отправляет мастеру задание	    
send_task(N,D,S,_,MasterPID) ->
    Task = fun(X, SlavePID) -> parrallel_cliques( N,
						  D,
						  S,
						  X,
						  SlavePID,
						  MasterPID)
	   end,
    MasterPID!{addTask, Task}.

finish(SlavePID, MasterPID) ->
    MasterPID!{finish, SlavePID}.
    
